package com.dapeng.keycloakspringdemo;

import org.keycloak.KeycloakPrincipal;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/users")
public class UserController {
    @Value("${keycloak.resource}")
    private String client;

    @GetMapping("/me")
    public ResponseEntity getLoginUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        KeycloakPrincipal principal = (KeycloakPrincipal) authentication.getPrincipal();
        String tokenString = principal.getKeycloakSecurityContext().getTokenString();
        Map<String, Object> map = new HashMap<>(2);
        map.put("userId", principal.getName());
        map.put("accessToken", tokenString);
        map.put("client", client);
        return ResponseEntity.ok(map);
    }
}
